package com.zsh.servlet;

import org.apache.commons.io.IOUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;

public class DownloadServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.获取要下载的文件名
        String downloadFilename = "qq.jpg";
        //2.读取需要下载的文件内容（通过ServletContext对象读取）
        ServletContext servletContext = getServletContext();

        //4.通过响应头告诉客户端数据类型
        //获取要下载的文件类型
        String mimeType = servletContext.getMimeType("/images/" + downloadFilename);
        response.setContentType(mimeType);

        //5.告诉客户端，收到的数据用于下载
        //Content-Disposition，数据然后处理
        //attachment 附件形式
        //URLEncoder.encode 转换编码 （火狐需要Base64编码）
        response.setHeader("Content-Disposition","attachment;filename=" + URLEncoder.encode("中国.jpg","UTF-8"));

        InputStream resourceAsStream = servletContext.getResourceAsStream("/images/" + downloadFilename);
        //获取响应的输出流
        ServletOutputStream outputStream = response.getOutputStream();
        //3.把下载的文件回传给客户端
        //读取输入流中的数据，复制给输出流
        IOUtils.copy(resourceAsStream, outputStream);


    }
}
